from PIL import Image
from math import sqrt
import glob, os
import commands

width = 320
height = 480

def CalcLayout(num_images):
  ratio = height / width
  num_across = sqrt(num_images * ratio)
  num_across = int(round(num_across + 0.5))
  num_down = num_images / num_across
  if num_across * num_down < num_images:
    num_down += 1
  return (num_across, num_down)

def CalcPwr2(dimensions):
  max_pixels = dimensions[0] * width
  if dimensions[1] * height > max_pixels:
    max_pixels = dimensions[1] * height
  pwr_2 = 1
  while pwr_2 < max_pixels:
    pwr_2 *= 2
  return pwr_2

def PngoutFile(filename):
  s,o = commands.getstatusoutput('~/dev/pyTexAtlas/pngout-darwin %s' % filename)
  if s != 0:
    print 'status: %s\noutput: %s' % (s, o)
    exit(0)

kPlistHeader = '''<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">\n<dict>\n'''

def CreateAtlas(atlas_filename):
  file_list = glob.glob("*.png")
  num_images = len(file_list)
  image_layout = CalcLayout(num_images)
  print image_layout
  image_size = CalcPwr2(image_layout)
  print image_size
  atlas_image = Image.new('RGBA', (image_size, image_size))
  cur_loc = (0, 0)
  plist = kPlistHeader
  for infile in file_list:
    im = Image.open(infile)
    if 'interlace' in im.info and im.info['interlace'] == 1:
      print '%s is interlaced, running pngout...' % infile
      PngoutFile(infile)
      im = Image.open(infile)
    upper_left = (cur_loc[0] * width, cur_loc[1] * height)
    atlas_image.paste(im, upper_left)
    plist += '  <key>%s</key>\n  <string>%d,%d</string>\n' % (infile, upper_left[0], upper_left[1])
    if cur_loc[0] + 1 < image_layout[1]:
      cur_loc = (cur_loc[0] + 1, cur_loc[1])
    else:
      cur_loc = (0, cur_loc[1] + 1)
  atlas_image.save(atlas_filename)
  plist += '</dict>\n</plist>'
  plist_file = file(atlas_filename + '.plist', 'w')
  plist_file.write(plist)
  plist_file.close()
  

CreateAtlas('atlas.png')
